from machine import Pin
from machine import FPIOA
import time

# 实例化FPIOA
fpioa = FPIOA()

fpioa.set_function(28, FPIOA.GPIO28)
fpioa.set_function(29, FPIOA.GPIO29)
fpioa.set_function(30, FPIOA.GPIO30)
fpioa.set_function(31, FPIOA.GPIO31)

fpioa.set_function(18, FPIOA.GPIO18)
fpioa.set_function(19, FPIOA.GPIO19)
fpioa.set_function(33, FPIOA.GPIO33)
fpioa.set_function(35, FPIOA.GPIO35)

# 创建行的对象
row1 = Pin(28, Pin.IN, Pin.PULL_DOWN)
row2 = Pin(29, Pin.IN, Pin.PULL_DOWN)
row3 = Pin(30, Pin.IN, Pin.PULL_DOWN)
row4 = Pin(31, Pin.IN, Pin.PULL_DOWN)
row_list = [row1, row2, row3, row4]  # 将创建的行对象放到list里面

# 创建列的对象
col1 = Pin(18, Pin.OUT)
col2 = Pin(19, Pin.OUT)
col3 = Pin(33, Pin.OUT)
col4 = Pin(35, Pin.OUT)
col_list = [col1, col2, col3, col4]  # 将创建的列对象放到list里面

# 键盘矩阵表，后面用来判断按下的是哪个按钮
names = [
    ["1", "2", "3", "4"],
    ["5", "6", "7", "8"],
    ["9", "10", "11", "12"],
    ["13", "14", "15", "16"]
]
def detect_key_press():
    """检测按键输入并返回按键名称"""
    key_pressed = None
    
    # 设置所有列为输出模式并拉低
    for col in col_list:
        col.value(0)
    
    # 逐行检测
    for j, row in enumerate(row_list):
        if row.value() == 0:  # 检测到按键按下
            # 消抖处理
            time.sleep_ms(20)
            if row.value() == 0:
                # 确定按下的是哪一列
                for i, col in enumerate(col_list):
                    col.value(1)  # 拉高当前列
                    time.sleep_ms(1)
                    if row.value() == 1:
                        key_pressed = names[j][i]
                        break
                    col.value(0)  # 恢复低电平
            # 等待按键释放
            while row.value() == 0:
                time.sleep_ms(10)
            break
    
    # 恢复所有引脚状态（修正此处）
    for col in col_list:
        col.init(mode=Pin.IN, pull=Pin.PULL_UP)  # 去掉 machine 前缀
    
    return key_pressed
# while True:
#     # enumerate多用于在for循环中得到计数，利用它可以同时获得索引和值，即需要index和value值的时候可以使用enumerate
#     for i, col in enumerate(col_list):  # 目的：只让某一列通电，其他的列都是0
#         for temp in col_list:  # 遍历列对象
#             temp.value(0)  # 给每一个列对象赋值
#         col.value(1)
#         time.sleep_ms(15)
#         for j, row in enumerate(row_list):  # 遍历序号和对应的值
#             if row.value() == 1:   # 给每一个行对象赋值
#                 print("按键: {} 被按下".format(names[j][i]))

#     time.sleep(0.1)
